﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Common;
using HanGu.Entity;
using HanGu.Services.Interface;
using HanGu.Entity.Enum;
using System.Threading;

namespace HanGu.CRM
{
    public class AdminBaseController : Controller
    {
        protected static readonly IMessage serviceMessage = ServiceFactory.GetService<IMessage>();
        protected static readonly IFileManage serviceFileManage = ServiceFactory.GetService<IFileManage>();
        protected static readonly IModule serviceModule = ServiceFactory.GetService<IModule>();
        protected static readonly IRoles serviceRoles = ServiceFactory.GetService<IRoles>();
        protected static readonly IDictionary serviceDictionary = ServiceFactory.GetService<IDictionary>();
        protected static readonly ISystemConfig serviceSystemConfig = ServiceFactory.GetService<ISystemConfig>();
        protected static readonly IManager servicesManager = ServiceFactory.GetService<IManager>();
        protected static readonly IGroup serviceGroup = ServiceFactory.GetService<IGroup>();
        protected static readonly IMemberInfo serviceMemberInfo = ServiceFactory.GetService<IMemberInfo>();
        protected static readonly IDictionary serviceDict = ServiceFactory.GetService<IDictionary>();
        protected static readonly IArea serviceArea = ServiceFactory.GetService<IArea>();
        protected static readonly IChangeGradeRecorde serviceUpGrade = ServiceFactory.GetService<IChangeGradeRecorde>();
        protected static readonly IChangeChargeRecorde serviceChangeCharge = ServiceFactory.GetService<IChangeChargeRecorde>();
        protected static readonly IChangeGradeRecorde serviceGrade = ServiceFactory.GetService<IChangeGradeRecorde>();
        protected static readonly IChargeRecorde serviceCharge = ServiceFactory.GetService<IChargeRecorde>();


        protected static readonly int pageSize = Helper.PageSize;
        protected string sort = "";
        protected string order = "";
        protected int pageNumber = 1;

        protected const string VIEWLIST = "~/Views/Admin/{0}/index.cshtml";
        protected const string VIEWCREATE = "~/Views/Admin/{0}/create.cshtml";
        /// <summary>
        /// 列表视图
        /// </summary>
        protected string viewList = string.Empty;
        /// <summary>
        /// 创建或修改视图
        /// </summary>
        protected string viewCreate = string.Empty;

        protected string ajaxStr = "\"statusCode\":\"{0}\", \"message\":\"{1}\", \"navTabId\":\"{2}\", \"forwardUrl\":\"{3}\", \"callbackType\":\"{4}\"";
        private UniversallySearchParam _SearchParma = new UniversallySearchParam() { Pagination = new PaginationDTO() { CurrentIndex = 1, PageSize = pageSize } };
        protected UniversallySearchParam SearchParma
        {
            get { return _SearchParma; }
            set { _SearchParma = value; }
        }

        /// <summary>
        /// navTab ID
        /// </summary>
        protected string navTabId = string.Empty;

        private CurrentUserDTO _CurentUser = new CurrentUserDTO() { UserName = "admin" };
        public CurrentUserDTO CurentUser
        {
            get
            {
                return _CurentUser;
            }
            set { _CurentUser = value; }
        }

        public string OperateID
        {
            get { return Session["OperateID"] as string; }
            set { Session["OperateID"] = ViewData["OperateID"] = value; }
        }

        [ValidateInput(false)]
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            SetUser();//测试用
            if (Session["CurentUser"] != null)
            {
                CurentUser = Session["CurentUser"] as CurrentUserDTO;
            }
            else
            {
                if (filterContext.RouteData.Values["controller"].ToString().ToLower() == "main")
                {
                    Response.Redirect("/login");
                }
                else
                {
                    Response.Clear();
                    Response.Write("{" + string.Format(ajaxStr, 500, ResourceManager.SessionOver, navTabId, "/Login", "forward") + "}");
                    Response.End();
                }
            }
            var area = filterContext.RouteData.DataTokens["area"];
            var controller = filterContext.RouteData.Values["controller"];
            var action = filterContext.RouteData.Values["action"];

            #region 设置当前页面
            int currentIndex = 1;
            if (Request["pageNum"] != null)
            {
                int.TryParse(Request["pageNum"], out currentIndex);
            }
            SearchParma.Pagination.CurrentIndex = currentIndex;
            #endregion

            #region 设置共用搜索参数
            if (CurentUser.SubManager != null && !Helper.SuperUsers.Contains(CurentUser.CurrentUserInfo.User))
            {
                SearchParma.SubAssignedIn = CurentUser.SubManager.Select(c => c.ID).ToList<int>();
                SearchParma.SubAssignedIn = SearchParma.SubAssignedIn ?? new List<int>();
                SearchParma.SubAssignedIn.Add(CurentUser.CurrentUserInfo.ID);
            }
            else//测试 
            {
                // SearchParma.SubAssignedIn = new List<int>() {1, 6 };
            }
            SearchParma.Ttile = Request["Title"];
            DateTime startime = DateTime.MinValue;
            DateTime endtime = DateTime.MinValue;
            if (Request["StarTime"] != null)
            {
                if (DateTime.TryParse(Request["StarTime"], out startime))
                {
                    { SearchParma.StarDateTime = startime; }
                }
            }
            if (Request["EndTime"] != null)
            {
                if (DateTime.TryParse(Request["EndTime"], out endtime))
                { SearchParma.EndDateTime = endtime; }
            }

            SearchParma.PalayAdress = Request["PalayAdress"];
            SearchParma.Lectcher = Request["Lectcher"];
            SearchParma.Degree = Request["Degree"];
            SearchParma.Creator = Request["Creator"];
            SearchParma.Updater = Request["Updater"];
            SearchParma.Suitabler = Request["Suitabler"];
            int IntObj1 = 0;
            if (!String.IsNullOrEmpty(Request["IntObj1"]))
            {
                int.TryParse(Request["IntObj1"], out IntObj1);
                SearchParma.IntObj1 = IntObj1;
            }
            if (!String.IsNullOrEmpty(Request["IntObj2"]))
            {
                int.TryParse(Request["IntObj2"], out IntObj1);
                SearchParma.IntObj2 = IntObj1;
            }
            if (!String.IsNullOrEmpty(Request["ClassType"]))
            {
                int.TryParse(Request["ClassType"], out IntObj1);
                SearchParma.ClassType = IntObj1;
            }
            if (!String.IsNullOrEmpty(Request["LectcherID"]))
            {
                int.TryParse(Request["LectcherID"], out IntObj1);
                SearchParma.LectcherID = IntObj1;
            }

            #endregion

            #region 设置是否需要重新计算总记录
            if (Request["RowCount"] != null)
            {
                int rowCount = 0;
                int.TryParse(Request["RowCount"], out rowCount);
                SearchParma.Pagination.RowCount = rowCount;
            }
            #endregion
            navTabId = string.Format("{0}{1}", area, controller);
            ViewData["CurrentController"] = navTabId;

            #region 初始化视图路径
            viewList = string.Format(VIEWLIST, navTabId);
            viewCreate = string.Format(VIEWCREATE, navTabId);
            #endregion

            #region 设置当前用户是否只能看下属
            if (CurentUser.Roles.Where(c => c.ID == "Users_6").FirstOrDefault() != null)
            {
                SearchParma.OnlySon = CurentUser.CurrentUserInfo.ID;
            }
            #endregion
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            ViewData["CurrentPageButtons"] = new List<VRolePurview>();
            if (CurentUser != null && CurentUser.Roles != null)
            {
                string currentUrl = Request.FilePath;
                var currentModule = CurentUser.Roles.Where(c => !string.IsNullOrEmpty(c.Url) && c.Url.IndexOf(currentUrl) >= 0 && c.Types == (int)CommEnum.ModuleTypes.模块).FirstOrDefault();
                var currentButtons = new List<VRolePurview>();
                var currentFuncs = new List<VRolePurview>();
                if (currentModule != null)
                {
                    currentButtons = CurentUser.Roles.Where(c => c.Parent == currentModule.ID && c.Types == (int)CommEnum.ModuleTypes.按钮).OrderBy(c => c.Order).ToList();
                    currentFuncs = CurentUser.Roles.Where(c => c.Parent == currentModule.ID && c.Types == (int)CommEnum.ModuleTypes.功能点).OrderBy(c => c.Order).ToList();
                }
                ViewData["CurrentPageButtons"] = currentButtons;
                ViewData["CurrentPageFuncs"] = currentFuncs;
            }

            int nPageSize = pageSize;
            if (SearchParma != null && SearchParma.Pagination != null)
            {
                if (SearchParma.Pagination.PageSize == Int32.MaxValue)
                    nPageSize = 0;
                if (SearchParma.Pagination.PageSize != 0)
                    nPageSize = SearchParma.Pagination.PageSize;
            }
            ViewData["pageSize"] = nPageSize;
            ViewData["PhotoWidth"] = Helper.PhotoWidth;
            ViewData["PhotoHeight"] = Helper.PhotoHeight;
            ViewData["SearchParma"] = SearchParma;
            LogOperation(filterContext);

        }
        protected void ExceptionHand(Exception e)
        {
            new Loger().ExceptionHand(e);
        }

        protected override void OnException(ExceptionContext errorContext)
        {
            errorContext.Result = new RedirectResult(Url.Action("Error", "Shared"));
        }

        protected virtual bool MoveToFile(string guid, string newFile, out string newpath)
        {
            bool tag = false;
            newpath = string.Empty;
            try
            {
                var fileManage = serviceFileManage.GetByGuid(guid);
                //string newFile = "Email";
                foreach (var item in fileManage)
                {
                    if (item.FilePath.IndexOf("Temp") > 0)
                    {
                        FileManagement.MoveToFile(item.FilePath, item.FilePath.Replace("Temp", newFile));
                        item.FilePath = item.FilePath.Replace("Temp", newFile);
                        newpath = item.FilePath;
                        serviceFileManage.Update(item);
                    }
                }
                tag = true;
            }
            catch
            { }
            return tag;

        }

        protected List<Manager> GetManagersByLevel(bool isLevel = true)
        {
            int? parentID = null;
            //if (CurentUser.Roles.Where(c => c.ID == "Users_6").FirstOrDefault() != null)
            //{
            //    parentID = CurentUser.CurrentUserInfo.ID;

            //}
            if (!Helper.SuperUsers.Contains(CurentUser.CurrentUserInfo.User.ToLower()))
            { parentID = CurentUser.CurrentUserInfo.ID; }
            return servicesManager.GetAllByLevel(parentID, isLevel);
        }

        protected SelectList GetListFromDict(string groupName, bool IsSelectLabel = false)
        {
            var lst = serviceDict.GetByGroupName(groupName);
            if (IsSelectLabel)
            {
                lst.Insert(0, new HanGu.Entity.Dictionary() { key = "-100", Value = HelperCommon.SelectDefaultValue });
            }
            SelectList sList = new SelectList(lst, "GenerateKey", "Value");
            return sList;
        }

        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="filterContext"></param>
        private void LogOperation(ActionExecutedContext filterContext)
        {
            string opID = Request["OpID"];
            //opID = opID ?? OperateID;
            OperateID = opID;
            if (!string.IsNullOrEmpty(opID))
            {
                var role = CurentUser.Roles.SingleOrDefault(c => c.ID == opID);
                if (role != null)
                {
                    var logOp = new OperationLogDTO();
                    logOp.ID = opID;
                    logOp.ModuleName = role.ModuleName;
                    logOp.URL = role.Url;
                    logOp.Detail = role.Title;
                    logOp.Operater = CurentUser.UserName;
                    logOp.OpTime = DateTime.Now;

                    string parameters = string.Empty;
                    foreach (var item in filterContext.RouteData.Values)
                    {
                        parameters += string.Format("{0}={1};", item.Key, item.Value);
                    }
                    logOp.Parameters = parameters;
                    logOp.OperateAction = filterContext.RequestContext.HttpContext.Request.HttpMethod;
                    //Thread thred = new Thread(new ParameterizedThreadStart(WriteOpLog));
                    //thred.Start(logOp);
                    string xml = XmlUtil.Serializer<OperationLogDTO>(logOp);
                    WriteFile wFile = new WriteFile("/OpLog/", LogType.Daily);
                    wFile.Write(new Msg() { Text = xml });
                }
            }
        }

        public void WriteOpLog(object logOp)
        {
            string OplogxmlfilePath = string.Format("{0}/{1}.xml", AppDomain.CurrentDomain.BaseDirectory + "/OpLog", DateTime.Now.ToString("yyyyMMdd"));
            HanGu.Common.XmlUtil.SerializerToFile<OperationLogDTO>(logOp as OperationLogDTO, OplogxmlfilePath);
        }
        void SetUser()
        {
            if (Session["CurentUser"] == null && Request.Cookies["User"] != null)
            {
                string user = Request.Cookies["User"].Value;
                CurrentUserDTO curentUser = new CurrentUserDTO();
                if (Helper.SuperUsers.Contains(user.ToLower()))
                {
                    if (user == "luochengbang")
                    {
                        curentUser = new CurrentUserDTO()
                        {
                            UserName = user,
                            CurrentUserInfo = new Manager()
                            {
                                User = user
                            }
                        };
                    }
                    else
                    {
                        curentUser.CurrentUserInfo = servicesManager.GetByUser(user);

                    }
                    List<VRolePurview> roles = new List<VRolePurview>();
                    var allRoles = HelperCommon.GetModulesFromXML().Where(c => c.Reverse == false || !c.Reverse.HasValue);
                    foreach (var c in allRoles)
                    {
                        roles.Add(
                            new VRolePurview()
                            {
                                Name = "超级管理员",
                                ModulelID = c.ID,
                                ID = c.ID,
                                Title = c.Title,
                                Url = c.Url,
                                Order = c.Order,
                                Remark = c.Remark,
                                GUID = c.GUID,
                                Types = c.Types,
                                ParmFormat = c.ParmFormat,
                                OnCilck = c.OnCilck,
                                Parent = c.Parent,
                                RoleID = -1,
                                CssClass = c.CssClass,
                                Target = c.Target,
                                Fresh = c.Fresh,
                                External = c.External,
                                ModuleName = c.ModuleName,
                                Warn = c.Warn

                            }
                            );
                    }
                    curentUser.Roles = roles;
                }
                else
                {
                    curentUser = servicesManager.GetByUserAndRoles(user);
                }

                Session["CurentUser"] = curentUser;

            }
        }
    }
}
